package com.jeecg.wb;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

public class Processor extends Thread{
	
	
	private Socket socket ;
	
	private InputStream in;
	
	private PrintStream out;
	
	private final static String WEB_ROOT ="c:\\moban1376\\";
	
	public Processor(Socket socket) {
		
		this.socket = socket;
		
		try {
			in = socket.getInputStream();
			
			out = new PrintStream(socket.getOutputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		try {
			
			String filename = parse(in);
			
			sendFile(filename);
		} catch (Exception e) {
			
			sendErrorMessage(404, "File not found");
			return ;
		}
		
	}
	
	public String parse(InputStream in){
		
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		String filename = null;
		
		try {
			String httpMessage = br.readLine();
			
			String[] content = httpMessage.split(" ");
			
			if(content.length!=3){
				
				sendErrorMessage(400, "Bad Request!");
				return null;
			}
			
			filename = content[1];
			
			

		} catch (IOException e) {
			
			sendErrorMessage(404, "File not found");

		}
		return filename;
	}
	
	public void sendErrorMessage(int errorCode,String message){
		
		out.println("HTTPS/1.1 "+errorCode+" "+message);
		out.println("content-type:text/html");
		out.println();
		out.println("<html>");
		out.println("<title> ERROR MESSAGE");
		out.println("</title>");
		out.println("<body>");
		out.println("<h1> errorcode "+errorCode+",message "+message);
		out.println("</body>");

		out.println("</html>");
		out.flush();
		out.close();

	}
	
	
	public void sendFile(String filename){
		
		File file = new File(WEB_ROOT+filename);
		
		
		System.out.println(file+"------");
		if(file==null||!file.exists()){
			
			sendErrorMessage(404, "File not found");
		}
		try {
			InputStream in = new FileInputStream(file);
			
			byte content[] = new byte[(int)file.length()];
			
			in.read(content);
			out.println("HTTPS/1.1 200 QUERYFILE");
			out.println("content-length:"+content.length);
			out.println();
			out.write(content);
			out.flush();
			out.close();
			in.close();
			
		} catch (Exception e) {
			
			sendErrorMessage(404, "File not found");
		}
		
		
		
		
		
	}
	
	public static void main(String[] args) {
		
		String httpMessage = "GET /index.html HTTP/1.1";
		
		String[] content = httpMessage.split(" ");
		
		System.out.println(content[1]);
		
		
	}
	
}
